/* author Angelo Selvini <info@endum.net> */

#include "base.h"
#include "log.h"
#include "buffer.h"
#include "response.h"
#include "connections.h"

#include "plugin.h"

#include <ctype.h>
#include <stdlib.h>
#include <string.h>

#include "inet_ntop_cache.h"

/* plugin config for all request/connections */
typedef struct {
	buffer *path;
	buffer *format;
} plugin_config;

typedef struct {
	PLUGIN_DATA;

	plugin_config **config_storage;
	plugin_config conf;
} plugin_data;

/* init the plugin data */
INIT_FUNC(mod_remotehost_init) {
	plugin_data *p;

	p = calloc(1, sizeof(*p));

	return p;
}

/* detroy the plugin data */
FREE_FUNC(mod_remotehost_free) {
	plugin_data *p = p_d;

	UNUSED(srv);

	if (!p) return HANDLER_GO_ON;

	if (p->config_storage) {
		size_t i;

		for (i = 0; i < srv->config_context->used; i++) {
			plugin_config *s = p->config_storage[i];

			if (!s) continue;

			buffer_free(s->path);
			buffer_free(s->format);

			free(s);
		}
		free(p->config_storage);
	}

	free(p);

	return HANDLER_GO_ON;
}


/* handle plugin config and check values */
SETDEFAULTS_FUNC(mod_remotehost_set_defaults) {
	plugin_data *p = p_d;
	size_t i = 0;

	config_values_t cv[] = {
		{ "remotehost.path",   NULL, T_CONFIG_STRING, T_CONFIG_SCOPE_CONNECTION },
		{ "remotehost.format", NULL, T_CONFIG_STRING, T_CONFIG_SCOPE_CONNECTION },
		{ NULL, NULL, T_CONFIG_UNSET, T_CONFIG_SCOPE_UNSET }
	};

	if (!p) return HANDLER_ERROR;

	p->config_storage = calloc(1, srv->config_context->used * sizeof(specific_config *));

	for (i = 0; i < srv->config_context->used; i++) {
		plugin_config *s;

		s = calloc(1, sizeof(plugin_config));
		s->path = buffer_init();
		s->format = buffer_init();

		cv[0].destination = s->path;
		cv[1].destination = s->format;

		p->config_storage[i] = s;

		if (0 != config_insert_values_global(srv, ((data_config *)srv->config_context->data[i])->value, cv)) {
			return HANDLER_ERROR;
		}
	}

	return HANDLER_GO_ON;
}

#define PATCH(x) \
	p->conf.x = s->x;
static int mod_remotehost_patch_connection(server *srv, connection *con, plugin_data *p) {
	size_t i, j;
	plugin_config *s = p->config_storage[0];

	PATCH(path);
	PATCH(format);

	/* skip the first, the global context */
	for (i = 1; i < srv->config_context->used; i++) {
		data_config *dc = (data_config *)srv->config_context->data[i];
		s = p->config_storage[i];

		/* condition didn't match */
		if (!config_check_cond(srv, con, dc)) continue;

		/* merge config */
		for (j = 0; j < dc->value->used; j++) {
			data_unset *du = dc->value->data[j];

			if (buffer_is_equal_string(du->key, CONST_STR_LEN("remotehost.path"))) {
				PATCH(path);
			}
			if (buffer_is_equal_string(du->key, CONST_STR_LEN("remotehost.format"))) {
				PATCH(format);
			}
		}
	}

	return 0;
}
#undef PATCH

/* handle output format versions */
static handler_t mod_remotehost_handle_remote_ip_text(buffer *queue, buffer *ip) {
	buffer_append_string_buffer(queue,ip);
	return 0;
}
static handler_t mod_remotehost_handle_remote_ip_xml(buffer *queue, buffer *ip) {
	buffer_append_string_len(queue, CONST_STR_LEN("<?xml version = \"1.0\"?>\n"
		"<!DOCTYPE ip [\n"
		"<!ELEMENT ip (#PCDATA)>\n"
		"]>\n<ip>"));
	buffer_append_string_buffer(queue,ip);
	buffer_append_string_len(queue, CONST_STR_LEN("</ip>"));
	return 0;
}
static handler_t mod_remotehost_handle_remote_ip_json(buffer *queue, buffer *ip) {
	buffer_append_string_len(queue, CONST_STR_LEN("{\"ip\":\""));
	buffer_append_string_buffer(queue,ip);
	buffer_append_string_len(queue, CONST_STR_LEN("\"}"));
	return 0;
}


/* handle rendering of ip by content-type required */
static handler_t mod_remotehost_handle_remote_ip(server *srv, connection *con, void *p_d) {
	plugin_data *p = p_d;
	buffer *ct;
	buffer *ip;
	buffer *b;

	b = chunkqueue_get_append_buffer(con->write_queue);
	ip = buffer_init();
	ct = buffer_init();

	// Get remote ip address, horray!
	buffer_append_string(ip, inet_ntop_cache_get_ip(srv, &(con->dst_addr)));

	if (buffer_is_empty(p->conf.format)) {
		buffer_append_string_len(p->conf.format, CONST_STR_LEN("text"));
	}

	// Handle output by format and define content-type
	if (0 == strncmp(p->conf.format->ptr, "xml", 3) ) {
		buffer_copy_string_len(ct, CONST_STR_LEN("text/xml"));
		mod_remotehost_handle_remote_ip_xml(b, ip);
	}
	else if (0 == strncmp(p->conf.format->ptr, "json", 3) ) {
		buffer_copy_string_len(ct, CONST_STR_LEN("application/json"));
		mod_remotehost_handle_remote_ip_json(b, ip);
	}
	else {
		buffer_copy_string_len(ct, CONST_STR_LEN("text/plain"));
		mod_remotehost_handle_remote_ip_text(b, ip);
	}

	response_header_overwrite(srv, con, CONST_STR_LEN("Content-Type"), ct->ptr, strlen(ct->ptr) );

	con->http_status = 200;
	con->file_finished = 1;

	buffer_free(ct);
	buffer_free(ip);

	return 0;
}

URIHANDLER_FUNC(mod_remotehost_uri_handler) {
	plugin_data *p = p_d;

	UNUSED(srv);

	if (con->mode != DIRECT)      return HANDLER_GO_ON;
	if (con->uri.path->used == 0) return HANDLER_GO_ON;

	mod_remotehost_patch_connection(srv, con, p);

	if (buffer_is_empty(p->conf.path)) return HANDLER_GO_ON;

	/* Active only on remotehost.path required*/
	if (0 == strcmp(p->conf.path->ptr, con->request.uri->ptr)) {
		mod_remotehost_handle_remote_ip(srv, con, p_d);
		return HANDLER_FINISHED;
	} else {
		return HANDLER_GO_ON;
	}

}


/* this function is called at dlopen() time and inits the callbacks */

int mod_remotehost_plugin_init(plugin *p) {
	p->version     = LIGHTTPD_VERSION_ID;
	p->name        = buffer_init_string("remotehost");

	p->init        = mod_remotehost_init;
	p->handle_uri_clean  = mod_remotehost_uri_handler;
	p->set_defaults  = mod_remotehost_set_defaults;
	p->cleanup     = mod_remotehost_free;

	p->data        = NULL;

	return 0;
}
